package com.ruoyi.tzai.controller;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tzai.domain.TaskQueue;
import com.ruoyi.tzai.domain.TaskStep;
import com.ruoyi.tzai.service.ITaskQueueService;
import com.ruoyi.tzai.service.ITaskStepService;
import com.ruoyi.tzai.service.task.ITaskExecutorService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 任务队列Controller
 * 
 * @author tzai
 * @date 2025-11-12
 */
@Api(tags = "任务队列管理")
@RestController
@RequestMapping("/tzai/task/queue")
public class TaskQueueController extends BaseController
{
    @Autowired
    private ITaskQueueService taskQueueService;

    @Autowired
    private ITaskStepService taskStepService;

    @Autowired
    private ITaskExecutorService taskExecutorService;

    /**
     * 查询任务队列列表
     */
    @ApiOperation("查询任务队列列表")
    @PreAuthorize("@ss.hasPermi('tzai:task:queue:list')")
    @GetMapping("/list")
    public TableDataInfo list(TaskQueue taskQueue)
    {
        startPage();
        List<TaskQueue> list = taskQueueService.selectTaskQueueList(taskQueue);
        return getDataTable(list);
    }

    /**
     * 导出任务队列列表
     */
    @ApiOperation("导出任务队列列表")
    @PreAuthorize("@ss.hasPermi('tzai:task:queue:export')")
    @Log(title = "任务队列", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TaskQueue taskQueue)
    {
        List<TaskQueue> list = taskQueueService.selectTaskQueueList(taskQueue);
        ExcelUtil<TaskQueue> util = new ExcelUtil<TaskQueue>(TaskQueue.class);
        util.exportExcel(response, list, "任务队列数据");
    }

    /**
     * 获取任务队列详细信息
     */
    @ApiOperation("获取任务队列详细信息")
    @PreAuthorize("@ss.hasPermi('tzai:task:queue:query')")
    @GetMapping(value = "/{taskId}")
    public AjaxResult getInfo(@PathVariable("taskId") Long taskId)
    {
        TaskQueue task = taskQueueService.getTaskStatus(taskId);
        if (task != null) {
            // 查询任务步骤
            List<TaskStep> steps = taskStepService.selectStepsByTaskId(taskId);
            task.setParams(new java.util.HashMap<String, Object>() {{
                put("steps", steps);
            }});
        }
        return success(task);
    }

    /**
     * 创建任务
     */
    @ApiOperation("创建任务")
    @PreAuthorize("@ss.hasPermi('tzai:task:queue:add')")
    @Log(title = "任务队列", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public AjaxResult create(@RequestBody TaskQueue taskQueue)
    {
        Long taskId = taskQueueService.createTask(taskQueue.getArticleId(), taskQueue.getConfig());
        return success(taskId);
    }

    /**
     * 提交任务（创建并立即执行）
     */
    @ApiOperation("提交任务")
    @PreAuthorize("@ss.hasPermi('tzai:task:queue:add')")
    @Log(title = "任务队列", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody TaskQueue taskQueue)
    {
        // 创建任务
        Long taskId = taskQueueService.createTask(taskQueue.getArticleId(), taskQueue.getConfig());
        
        // 提交执行
        taskQueueService.submitTask(taskId);
        taskExecutorService.executeTask(taskId);
        
        return success(taskId);
    }

    /**
     * 暂停任务
     */
    @ApiOperation("暂停任务")
    @PreAuthorize("@ss.hasPermi('tzai:task:queue:edit')")
    @Log(title = "任务队列", businessType = BusinessType.UPDATE)
    @PutMapping("/pause/{taskId}")
    public AjaxResult pause(@PathVariable Long taskId)
    {
        taskQueueService.pauseTask(taskId);
        return success();
    }

    /**
     * 继续任务
     */
    @ApiOperation("继续任务")
    @PreAuthorize("@ss.hasPermi('tzai:task:queue:edit')")
    @Log(title = "任务队列", businessType = BusinessType.UPDATE)
    @PutMapping("/resume/{taskId}")
    public AjaxResult resume(@PathVariable Long taskId)
    {
        taskQueueService.resumeTask(taskId);
        taskExecutorService.executeTask(taskId);
        return success();
    }

    /**
     * 取消任务
     */
    @ApiOperation("取消任务")
    @PreAuthorize("@ss.hasPermi('tzai:task:queue:edit')")
    @Log(title = "任务队列", businessType = BusinessType.UPDATE)
    @PutMapping("/cancel/{taskId}")
    public AjaxResult cancel(@PathVariable Long taskId)
    {
        taskQueueService.cancelTask(taskId);
        return success();
    }

    /**
     * 重试任务
     */
    @ApiOperation("重试任务")
    @PreAuthorize("@ss.hasPermi('tzai:task:queue:edit')")
    @Log(title = "任务队列", businessType = BusinessType.UPDATE)
    @PutMapping("/retry/{taskId}")
    public AjaxResult retry(@PathVariable Long taskId)
    {
        taskQueueService.retryTask(taskId);
        taskExecutorService.executeTask(taskId);
        return success();
    }

    /**
     * 修改任务队列
     */
    @ApiOperation("修改任务队列")
    @PreAuthorize("@ss.hasPermi('tzai:task:queue:edit')")
    @Log(title = "任务队列", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TaskQueue taskQueue)
    {
        return toAjax(taskQueueService.updateTaskQueue(taskQueue));
    }

    /**
     * 删除任务队列
     */
    @ApiOperation("删除任务队列")
    @PreAuthorize("@ss.hasPermi('tzai:task:queue:remove')")
    @Log(title = "任务队列", businessType = BusinessType.DELETE)
	@DeleteMapping("/{taskIds}")
    public AjaxResult remove(@PathVariable Long[] taskIds)
    {
        return toAjax(taskQueueService.deleteTaskQueueByTaskIds(taskIds));
    }
}

